package com.example.interceptor;

import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created with IntelliJ IDEA.
 * Description:1.定义拦截器
 * User: bjc
 * Date: 2025-08-04
 * Time: 20:55
 */
@Slf4j
@Component // 将当前类交给Spring管理
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //1.从header中获取 token，注意要和前端中设置的名称一样
        String token = request.getHeader("user_token_header");
        log.info("获取到的token：{}",token);
        //2.校验用户token
        Claims claims = JwtUtils.parseJwt(token);
        if(claims == null){
            //设置用户状态码401表示校验失败
            response.setStatus(401);
            log.error("用户未登录");
            return false;//拦截器返回false，请求被拦截
        }
        return true;//拦截器返回true，请求通过
    }
}
